package org.ccay.core.scheduler.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.impl.CommonApplicationException;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.scheduler.IMaintenanceTask;
import org.ccay.core.scheduler.ITimerTask;

/**
 * 
 * 获取多用户的定时任务,通过定时调度平台调用
 * 
 * @author chaowangbang
 * @since 2012-11-2
 */
@Named("ITimerTask.Maintenance")
public class MaintenanceTask implements ITimerTask {
	private final ILogger logger = CcayLoggerFactory.getLogger(MaintenanceTask.class);

	/**
	 * 执行任务
	 * 
	 * @param parameters
	 *            URL 中的参数 MAP
	 */
	public void executeOnTime(Map<String, String> parameters) throws ApplicationException {
		// 获取实现接口的所有方法
		Map<String, IMaintenanceTask> taskList = Ccay.getContext().getBeansOfType(IMaintenanceTask.class);
		List<String> errorTasks = new ArrayList<String>();
		// 执行方法并捕捉异常，记录异常和发生异常的任务名称
		for (Map.Entry<String, IMaintenanceTask> entry : taskList.entrySet()) {
			try {
				entry.getValue().executeOnTime(parameters);
			} catch (ApplicationException e) {
				errorTasks.add(entry.getKey());
				logger.error(e);
			} catch (RuntimeException e) {
				errorTasks.add(entry.getKey());
				logger.error(e);
			}
		}

		check(errorTasks);
	}

	// 拼接异常任务名称，并拋出
	public void check(List<String> errorTasks) throws ApplicationException {
		if (!errorTasks.isEmpty()) {
			StringBuilder erroTaskNames = new StringBuilder();
			boolean first = true;
			for (String key : errorTasks) {
				// 第一个不加逗号
				if (!first) {
					erroTaskNames.append(", ");
				}
				first = false;
				erroTaskNames.append(key);
			}
			throw new CommonApplicationException("Error tasks:" + erroTaskNames);
		}

	}

}
